﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CaiyinSoft.NetGather.Protocol;

namespace CaiyinSoft.NetGather.NetGatherLib.Filter
{
    [Serializable]
    public class RegexHTMLAnalyze : HTMLFilterBase
    {

        public override string FilterCaption
        {
            get
            {
                return "正则表达式过滤器";
            }
        }

        public override string ExpressionCaption
        {
            get
            {
                return "正则表达式";
            }
        }

        public override string Description
        {
            get
            {
                return "通过正则表达式过滤数据";
            }
        }

        public RegexHTMLAnalyze()
            :base()
        { 
            _InitParams();
        }

        private void _InitParams()
        {
            SetInputHTML("");
            OutputKey = Guid.NewGuid().ToString();
            //OutputType = 0;
            //ParseType = 1;
            FilterExpression = "";
        }


        /// <summary>
        /// 以指定方式解析HTML字符串，生成新字符串
        /// </summary>
        /// <returns></returns>
        public override List<FilterResult> FilterHTML()
        {
            return _RegexParseHTML();
        }

        private List<FilterResult> _RegexParseHTML()
        {
            int parentHTMLPosition = 0;
            if (ParentFilter != null)
                parentHTMLPosition = ParentFilter.HTMLPosition;
            HTMLPosition = parentHTMLPosition;

            List<FilterResult> parentResults = GetInputHTML();
            if (parentResults == null || parentResults.Count==0) return null;
            List<FilterResult> listRevalue = new List<FilterResult>();
            //foreach (var pr in parentResults)
            //{
            //}
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(FilterExpression);
            System.Text.RegularExpressions.MatchCollection matchs;  
            foreach(var pr in parentResults)
            {
                matchs = reg.Matches(pr.HTMLResult);
                foreach (System.Text.RegularExpressions.Match match in matchs)
                {
                    HTMLPosition = Math.Max(HTMLPosition, parentHTMLPosition + match.Index);
                    FilterResult result = new FilterResult();
                    result.HTMLPosition = pr.HTMLPosition + match.Index;
                    result.HTMLResult= string.Format("{0}", match.Value);
                    listRevalue.Add(result);
                }
            }
            
            return listRevalue;
        }

    }
}
